package com.crack.nga2.volley;

import android.util.Log;

import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 图片地址请求
 * Created by lenovo on 2016/1/12.
 */
public class PhotoUrlRequest extends BaseRequest<String> {
    private Response.Listener<String> listener;

    public PhotoUrlRequest(int method, String url, Response.Listener<String> listener) {
        super(method, url, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("error","error-->"+error);
            }
        });
        this.listener = listener;
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String string;
        try {
            string = new String(response.data,"GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Response.error(new VolleyError(e.getMessage()));
        }
        Pattern p = Pattern.compile("\"0\":\"(.*?)\"");
        Matcher matcher = p.matcher(string);
        if(matcher.find()){
            Log.i("tag",matcher.group(1));
            return Response.success(matcher.group(1), HttpHeaderParser.parseCacheHeaders(response));
        }
        return Response.error(new VolleyError("图片未找到"));
    }

    @Override
    protected void deliverResponse(String response) {
        if(listener!=null){
            listener.onResponse(response);
        }
    }
}
